<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>简易富文本编辑器</title>
    <style>
        #editor {
            width: 400px;
            height: 600px;
            border: 1px solid #ccc;
            padding: 10px;
            overflow-y: auto;
            position: relative;

            & h1 {
                margin: 50px 0;
                border: 1px solid;
            }
        }

        .tipBox {
            width: 100%;
            height: 5px;
            background: red;
            position: absolute;
            left: 0;
        }
    </style>
</head>

<body>
    <div id="editor" contenteditable="true">
        <h1 draggable="false" style="-webkit-user-drag: none;">标题1</h1>
        <h1>标题2</h1>
        <h1>标题3</h1>
        <h1>标题4</h1>
        <h1>标题5</h1>

        <div class="draggableTip"></div>
    </div>
    <button id="increaseFontSize">增大字体</button>
    <button id="decreaseFontSize">减小字体</button>

    <div id="draggable" draggable="true">
        我可以拖动 <br>
        我可以拖动 <br>
        我可以拖动 <br>
    </div>
    <script>
        // 竞品网站gamma：https://gamma.app/
        document.addEventListener('DOMContentLoaded', () => {
            const editor = document.getElementById('editor');
            const increaseFontSizeBtn = document.getElementById('increaseFontSize');
            const decreaseFontSizeBtn = document.getElementById('decreaseFontSize');


            function changeFontSize(direction) {
                const cursorInfo = getCursorPositionInEditor(editor);
                console.log(cursorInfo);

                const selection = window.getSelection();
                if (!selection.isCollapsed) {
                    const range = selection.getRangeAt(0);
                    let span;

                    if (range.commonAncestorContainer.nodeType === Node.TEXT_NODE) {
                        span = document.createElement('span');
                        range.surroundContents(span);
                    } else {
                        span = range.commonAncestorContainer.querySelector('span') || range.commonAncestorContainer;
                    }

                    const currentSize = parseInt(window.getComputedStyle(span).fontSize, 10);
                    const newSize = direction === 'increase' ? currentSize + 2 : Math.max(currentSize - 2, 10); // 增大或减小字体大小，最小限制为10px
                    span.style.fontSize = newSize + 'px';
                }
            }

            increaseFontSizeBtn.addEventListener('click', () => changeFontSize('increase'));
            decreaseFontSizeBtn.addEventListener('click', () => changeFontSize('decrease'));

            initDragged()


            // document.addEventListener('click', (event) => {
            //     event.preventDefault()
            //     let target = event.target
            //     console.log('当前点击的元素: ', target)
            // })

            // editor.addEventListener("selectionchange", (event) => {
            document.addEventListener("selectionchange", (event) => {
                event.preventDefault()
                let target = event.target
                console.log('selectionchange: ', target, target === document)
                console.log('selectionchange: ', document.getSelection())
            });
        });

        function getCursorPositionInEditor(editorElement) {
            const selection = window.getSelection();

            // 检查是否有选区，没有选区时光标位置实际上是指插入点位置
            if (selection.rangeCount > 0) {
                const range = selection.getRangeAt(0);
                const node = range.startContainer;

                // 获取光标相对于编辑器元素的位置
                if (node.parentNode === editorElement) {
                    // 光标位于编辑器内的文本节点
                    const offset = range.startOffset;
                    return { container: node, offset };
                } else {
                    // 光标可能位于编辑器内的某个子元素内，需要递归查找
                    // 这里提供一个简单的递归逻辑，实际情况可能更为复杂
                    let offset = 0;
                    let currentNode = node;
                    while (currentNode && currentNode !== editorElement) {
                        if (currentNode.nodeType === Node.TEXT_NODE) {
                            offset += range.startOffset;
                        }
                        currentNode = currentNode.parentNode;
                    }
                    return { container: editorElement.firstChild, offset }; // 返回第一个文本节点及相对偏移量
                }
            } else {
                return null; // 当前没有选区或光标位置
            }
        }

        // 使用示例
        // const editor = document.getElementById('editor');
        // const cursorInfo = getCursorPositionInEditor(editor);
        // console.log(cursorInfo);

        function initDragged() {
            let dragged = null;

            const source = document.getElementById("draggable");
            source.addEventListener("dragstart", (event) => {
                // 保存被拖动元素的引用
                dragged = event.target.cloneNode(true);
            });

            const target = document.getElementById("editor");

            const tipBox = document.createElement("div")
            tipBox.className = 'tipBox'
            target.appendChild(tipBox)
            let top = 0
            target.addEventListener("dragover", (event) => {
                // 阻止默认行为以允许放置
                event.preventDefault();
                if (!dragged) {
                    return
                }
                console.log('isTarget', event.pageX, event.pageY)
                const isTarget = event.target === target
                console.log('isTarget', isTarget)
                top = event.pageY
                tipBox.style.top = event.pageY + 'px'
                if (isTarget) {
                    // target.appendChild(tipBox)
                } else {
                    // event.target.appendChild(tipBox)
                }

            });

            target.addEventListener("drop", (event) => {
                // 阻止默认行为（会作为某些元素的链接打开）
                event.preventDefault();
                if (!dragged) {
                    return
                }
                // console.log(event)
                // 将被拖动的元素移动到选定的放置目标
                // if (event.target.className === "dropzone") {
                // dragged.parentNode.removeChild(dragged);

                for (const child of target.children) {
                    let a = top > child.getBoundingClientRect().top
                    console.log('top', top, child.getBoundingClientRect().top, a)
                    if (!a) {
                        target.insertBefore(dragged, child)
                        break
                    }
                }
                // event.target.appendChild(dragged);
                // }
                dragged = null
            });
        }

    </script>
</body>

</html>